<template>
    <div class="box">
        <header>
            <!-- <van-nav-bar title="登录" left-text="返回" left-arrow @click-left="$router.back()" /> -->
            <NavBar title="登录" />
        </header>
        <div class="content">
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="username" name="username" label="用户名" placeholder="请输入用户名"
                        :rules="[{ required: true, message: '请填写用户名' }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号' }]" />
                    <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                        :rules="[{ required: true, message: '请填写密码' }]" />
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">
                        提交
                    </van-button>
                </div>
                <van-row justify="space-between" style="text-align:center">
                    <van-col span="12">忘记密码</van-col>
                    <van-col span="12" @click="$router.push('/register')">快速注册</van-col>
                </van-row>
            </van-form>
        </div>
    </div>
</template>
<script>
import { ref } from 'vue';
import request from '@/utils/request';
import { useRouter } from "vue-router";  // 1.引入路由函数
import { showSuccessToast, showFailToast } from 'vant';
import NavBar from '@/components/NavBar.vue';
export default {
    components: {
        NavBar
    },
    setup() { // setup函数是组合式API不存在this
        const username = ref('');
        const password = ref('');
        const router = useRouter(); // 2.定义路由对象
        const onSubmit = (values) => {
            console.log('submit', values);
            request.post('/login', values).then(res => {
                if (res.data.code === 200) {
                    // 说明登录成功了
                    showSuccessToast('登录成功');
                    // 存储token
                    localStorage.setItem('token', res.data.token);
                    localStorage.setItem('username', username.value);
                    // 跳转到首页
                    router.replace('/home'); // 3. 实现跳转
                } else {
                    showFailToast(res.data.message);
                }
            })
        };
        return {
            username,
            password,
            onSubmit,
        };
    },
};
</script>
<style scoped>
.content {
    padding-top: 40px;
}
</style>